#! /usr/bin/env python
#-*- coding: utf-8 -*-
import os, DiscID
import CDDB
from mutagen.mp3 import MP3
    
def diskid (rep):
    fileExt = ['.mp3','.MP3','.Mp3','.mP3']
    files = [filename for filename in os.listdir(rep) if os.path.isfile(os.path.join(rep, filename))]
    files = [f for f in files if os.path.splitext(f)[1] in fileExt]
    files.sort()
    
    cd=0
    checksum=0
    tracks=[]
    
    nbr=len(files)
    for index in range(0,nbr):
        audio=MP3(os.path.join(rep,files[index-1]))
        length=int(audio.info.length*1000)
        bitrate=audio.info.bitrate
        if (index==0):
            length=2000
        cd=cd+length
        minutes=cd/60000
        secs=(cd%60000)/1000
        frames=(((cd%60000)%1000)*75)/1000
        print '%02d:%02d.%02d %s %s' %(minutes,secs,frames,length,files[index-1])
        checksum = checksum + DiscID.cddb_sum(minutes*60 + secs)
        tracks.append(minutes*60*75 + secs*75 + frames)
    ##
    audio=MP3(os.path.join(rep,files[-1]))
    length=int(audio.info.length*1000)
    bitrate=audio.info.bitrate
    cd=cd+length
    minutes=cd/60000
    secs=(cd%60000)/1000
    frames=(((cd%60000)%1000)*75)/1000
    tracks.append(minutes*60*75 + secs*75 + frames)
    ##
    
    total=(tracks[-1] / 75) - (tracks[0] / 75)
    
    discid = ((checksum % 0xff) << 24 | total << 8 | nbr)
    #x << y  ==   x * (2 ** y)
    return [discid, nbr] + tracks[:-1] + [ tracks[-1] / 75 ]

test=diskid("/media/sda6/Stockage Mp3/Daft Punk/Discovery")
print "--"
print "DiscID :"
print test
(query_status, query_info) = CDDB.query(test,"http://tracktype.org/~cddb/cddb.cgi")
if (query_status==202): print "No informations for this discID"
else: print query_info